package com.demo.arthas.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Random;

/**
 * @author peter
 * @date 2022/2/24 22:02
 */
@RestController
public class DeadLockController {

    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    @GetMapping("/dead/lock")
    public String deadLock() {
        new Thread(()->{
            synchronized (lock1) {
                sleep(1000);
                System.out.println("线程1, 等lock2");
                synchronized (lock2) {
                    System.out.println("线程1完成");
                }
            }
        }).start();

        new Thread(()->{
            synchronized (lock2) {
                sleep(1000);
                System.out.println("线程2, 等lock1");
                synchronized (lock1) {
                    System.out.println("线程2完成");
                }
            }
        }).start();
        return "ok";
    }

    private static void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
